package com.xu.hutool;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.signers.AlgorithmUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import cn.hutool.crypto.KeyUtil;
import org.junit.Test;

/**
 * hutool jwt
 *
 * @author Tom
 * @date 2021/07/27
 */
public class Hutool_JWT {
    public static void main(String[] args) {
        byte[] key = "1234567890".getBytes();
        String id = "rs256";
        JWTSigner signer = JWTSignerUtil.createSigner(id, KeyUtil.generateKeyPair(AlgorithmUtil.getAlgorithm(id)));
        String token = JWT.create()
                .setPayload("sub", "1234567890")
                .setPayload("name", "looly")
                .setPayload("admin", true)
//                .setKey(key)
                .setSigner(signer)
                .sign();
        System.out.println(token);
    }

    /**
     * jwt解析
     */
    @Test
    public void JWTAnalysis() {

        String rightToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." +
                "eyJzdWIiOiIxMjM0NTY3ODkwIiwiYWRtaW4iOnRydWUsIm5hbWUiOiJsb29seSJ9." +
                "536690902d931d857d2f47d337ec81048ee09a8e71866bcc8404edbbcbf4cc40";
        JWT jwt = JWT.of(rightToken);
        // JWT
        jwt.getHeader(JWTHeader.TYPE);
        // HS256
        Object header = jwt.getHeader(JWTHeader.ALGORITHM);

        // 1234567890
        System.out.println(jwt.getPayload("sub"));
        // looly
        System.out.println(jwt.getPayload("name"));
        // true
        System.out.println(jwt.getPayload("admin"));

    }


    @Test
    public void JWTVerify() {
        String rightToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." +
                "eyJzdWIiOiIxMjM0NTY3ODkwIiwiYWRtaW4iOnRydWUsIm5hbWUiOiJsb29seSJ9." +
                "536690902d931d857d2f47d337ec81048ee09a8e71866bcc8404edbbcbf4cc40";

        // 秘钥
        byte[] key = "1234567890".getBytes();
        // 默认验证HS265的算法
        System.out.println(JWT.of(rightToken).setKey(key).verify());
        String json = "{\"id\": 12, \"name\": \"alice\", \"address\": \"南京\"}";

    }

}
